<template>
  <div class="permission-settings-container">
    <!-- 页面标题 -->
    <div class="page-header mb-6">
      <h1 class="text-2xl font-bold text-gray-800">权限设置</h1>
      <p class="text-gray-500 mt-1">管理系统权限项及权限分组</p>
    </div>

    <!-- 操作栏 -->
    <div class="action-bar bg-white rounded-lg shadow-sm p-4 mb-6">
      <div class="flex flex-col md:flex-row md:items-center justify-between gap-4">
        <!-- 权限组选择 -->
        <div class="flex flex-wrap items-center gap-3">
          <select
            v-model="selectedGroupId"
            class="border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500 transition-all"
            @change="loadPermissionsByGroup"
          >
            <option value="">所有权限组</option>
            <option v-for="group in permissionGroups" :key="group.id" :value="group.id">{{ group.name }}</option>
          </select>

          <button
            class="bg-emerald-600 hover:bg-emerald-700 text-white px-4 py-2 rounded-lg transition-all flex items-center gap-2"
            @click="showAddPermissionModal = true"
          >
            <i class="fa fa-plus"></i>
            <span>新增权限</span>
          </button>

          <button
            class="bg-emerald-600 hover:bg-emerald-700 text-white px-4 py-2 rounded-lg transition-all flex items-center gap-2"
            @click="showAddGroupModal = true"
          >
            <i class="fa fa-folder-plus"></i>
            <span>新增权限组</span>
          </button>
        </div>

        <!-- 搜索框 -->
        <div class="relative w-full md:w-64">
          <input
            v-model="searchQuery"
            type="text"
            placeholder="搜索权限..."
            class="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500 transition-all"
            @keyup.enter="loadPermissionsByGroup"
          >
          <i class="fa fa-search absolute left-3 top-1/2 -translate-y-1/2 text-gray-400"></i>
        </div>
      </div>
    </div>

    <!-- 权限列表 -->
    <div class="permission-list bg-white rounded-lg shadow-sm overflow-hidden">
      <!-- 权限组折叠面板 -->
      <div v-for="group in filteredGroups" :key="group.id" class="border-b border-gray-200 last:border-0">
        <div 
          class="px-6 py-4 flex items-center justify-between cursor-pointer hover:bg-gray-50 transition-colors"
          @click="toggleGroup(group.id)"
        >
          <div class="flex items-center">
            <i 
              class="fa mr-3" 
              :class="isGroupOpen(group.id) ? 'fa-chevron-down text-emerald-600' : 'fa-chevron-right text-gray-500'"
            ></i>
            <div class="font-medium text-gray-900">{{ group.name }}</div>
            <span class="ml-2 text-sm text-gray-500">({{ group.permissions.length }} 项权限)</span>
          </div>
          <div class="flex items-center gap-2">
            <button
              class="text-blue-600 hover:text-blue-900 p-1"
              @click.stop="editGroup(group)"
              title="编辑权限组"
            >
              <i class="fa fa-edit"></i>
            </button>
            <button
              class="text-red-600 hover:text-red-900 p-1"
              @click.stop="confirmDeleteGroup(group)"
              title="删除权限组"
              :disabled="group.isSystemGroup || group.permissions.length > 0"
            >
              <i class="fa fa-trash"></i>
            </button>
          </div>
        </div>

        <!-- 权限项列表 -->
        <div v-if="isGroupOpen(group.id)" class="bg-gray-50 pl-16 pb-4">
          <div v-if="group.permissions.length === 0" class="px-6 py-6 text-center text-gray-500 text-sm">
            该权限组暂无权限项
          </div>
          
          <div v-else class="divide-y divide-gray-200">
            <div 
              v-for="permission in group.permissions" 
              :key="permission.id"
              class="px-6 py-3 flex items-center justify-between hover:bg-white transition-colors"
            >
              <div class="flex-1 min-w-0">
                <div class="font-medium text-gray-900 truncate">{{ permission.name }}</div>
                <div class="text-xs text-gray-500 font-mono mt-1">{{ permission.code }}</div>
                <div class="text-sm text-gray-600 mt-1 line-clamp-2">{{ permission.description || '无描述' }}</div>
              </div>
              
              <div class="flex items-center gap-2 ml-4">
                <button
                  class="text-blue-600 hover:text-blue-900 p-1"
                  @click="editPermission(permission)"
                  title="编辑权限"
                  :disabled="permission.isSystemPermission"
                >
                  <i class="fa fa-edit"></i>
                </button>
                <button
                  class="text-red-600 hover:text-red-900 p-1"
                  @click="confirmDeletePermission(permission)"
                  title="删除权限"
                  :disabled="permission.isSystemPermission"
                >
                  <i class="fa fa-trash"></i>
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-if="!loading && filteredGroups.length === 0" class="px-6 py-16 text-center">
        <div class="inline-flex items-center justify-center w-16 h-16 rounded-full bg-gray-100 mb-4">
          <i class="fa fa-key text-2xl text-gray-400"></i>
        </div>
        <h3 class="text-lg font-medium text-gray-900 mb-1">没有找到权限</h3>
        <p class="text-gray-500 max-w-md mx-auto">
          {{ searchQuery ? '没有匹配搜索条件的权限，请尝试其他关键词。' : '系统中暂无权限，请添加权限项。' }}
        </p>
        <button
          v-if="searchQuery"
          class="mt-4 text-emerald-600 hover:text-emerald-800 text-sm"
          @click="resetFilters"
        >
          清除筛选条件
        </button>
      </div>

      <!-- 加载状态 -->
      <div v-if="loading" class="px-6 py-16">
        <div v-for="i in 3" :key="i" class="mb-6 animate-pulse">
          <div class="h-6 bg-gray-200 rounded w-40 mb-4"></div>
          <div class="pl-8">
            <div v-for="j in 2" :key="j" class="h-4 bg-gray-200 rounded w-64 mb-2"></div>
            <div class="h-3 bg-gray-200 rounded w-48 mb-4"></div>
          </div>
        </div>
      </div>
    </div>

    <!-- 新增/编辑权限模态框 -->
    <PermissionModal
      :visible="showAddPermissionModal || showEditPermissionModal"
      :permission="selectedPermission"
      :permissionGroups="permissionGroups"
      :title="showAddPermissionModal ? '新增权限' : '编辑权限'"
      @close="() => { showAddPermissionModal = false; showEditPermissionModal = false; }"
      @save="handleSavePermission"
    />

    <!-- 新增/编辑权限组模态框 -->
    <PermissionGroupModal
      :visible="showAddGroupModal || showEditGroupModal"
      :group="selectedGroup"
      :title="showAddGroupModal ? '新增权限组' : '编辑权限组'"
      @close="() => { showAddGroupModal = false; showEditGroupModal = false; }"
      @save="handleSaveGroup"
    />

    <!-- 确认删除模态框 -->
    <ConfirmModal
      :visible="showConfirmModal"
      :title="confirmTitle"
      :message="confirmMessage"
      danger-text="删除"
      @close="showConfirmModal = false"
      @confirm="handleConfirmDelete"
    />
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue';
import PermissionModal from './components/PermissionModal.vue';
import PermissionGroupModal from './components/PermissionGroupModal.vue';
import ConfirmModal from '@/components/ConfirmDialog.vue';
import { usePermissionStore } from '@/stores/permissionStore';

export default {
  components: {
    PermissionModal,
    PermissionGroupModal,
    ConfirmModal
  },
  setup() {
    // 状态管理
    const permissionStore = usePermissionStore();

    // 数据状态
    const permissionGroups = ref([]);
    const loading = ref(false);
    
    // 筛选状态
    const searchQuery = ref('');
    const selectedGroupId = ref('');
    const expandedGroups = ref([]);
    
    // 模态框状态
    const showAddPermissionModal = ref(false);
    const showEditPermissionModal = ref(false);
    const showAddGroupModal = ref(false);
    const showEditGroupModal = ref(false);
    const showConfirmModal = ref(false);
    const selectedPermission = ref(null);
    const selectedGroup = ref(null);
    const itemToDelete = ref(null);
    const itemType = ref(''); // 'permission' 或 'group'
    
    // 确认框信息
    const confirmTitle = ref('');
    const confirmMessage = ref('');

    // 获取所有权限组及权限
    const fetchPermissionGroups = async () => {
      try {
        loading.value = true;
        const response = await permissionStore.getPermissionGroupsWithPermissions();
        permissionGroups.value = response;
        
        // 默认展开第一个组
        if (response.length > 0 && expandedGroups.value.length === 0) {
          expandedGroups.value.push(response[0].id);
        }
      } catch (error) {
        console.error('获取权限组失败:', error);
        // 可以在这里添加错误提示
      } finally {
        loading.value = false;
      }
    };

    // 根据选择的组和搜索条件筛选权限
    const filteredGroups = computed(() => {
      return permissionGroups.value
        .filter(group => {
          // 筛选组
          if (selectedGroupId.value && group.id !== selectedGroupId.value) {
            return false;
          }
          
          // 筛选权限
          const filteredPermissions = group.permissions.filter(permission => {
            const matchesSearch = !searchQuery.value || 
              permission.name.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
              permission.code.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
              (permission.description && permission.description.toLowerCase().includes(searchQuery.value.toLowerCase()));
            return matchesSearch;
          });
          
          // 更新组内权限列表
          group.permissions = filteredPermissions;
          return filteredPermissions.length > 0 || !searchQuery.value;
        });
    });

    // 切换组的展开/折叠状态
    const toggleGroup = (groupId) => {
      const index = expandedGroups.value.indexOf(groupId);
      if (index > -1) {
        expandedGroups.value.splice(index, 1);
      } else {
        expandedGroups.value.push(groupId);
      }
    };

    // 检查组是否展开
    const isGroupOpen = (groupId) => {
      return expandedGroups.value.includes(groupId);
    };

    // 根据组ID加载权限
    const loadPermissionsByGroup = () => {
      // 如果选择了新的组，自动展开
      if (selectedGroupId.value && !isGroupOpen(selectedGroupId.value)) {
        expandedGroups.value = [selectedGroupId.value];
      }
    };

    // 编辑权限
    const editPermission = (permission) => {
      selectedPermission.value = { ...permission };
      showEditPermissionModal.value = true;
    };

    // 编辑权限组
    const editGroup = (group) => {
      selectedGroup.value = { ...group };
      showEditGroupModal.value = true;
    };

    // 确认删除权限
    const confirmDeletePermission = (permission) => {
      itemToDelete.value = permission;
      itemType.value = 'permission';
      confirmTitle.value = '删除权限';
      confirmMessage.value = `确定要删除权限 "${permission.name}" 吗？此操作不可撤销，使用该权限的角色将受到影响。`;
      showConfirmModal.value = true;
    };

    // 确认删除权限组
    const confirmDeleteGroup = (group) => {
      itemToDelete.value = group;
      itemType.value = 'group';
      confirmTitle.value = '删除权限组';
      confirmMessage.value = `确定要删除权限组 "${group.name}" 吗？此操作不可撤销。`;
      showConfirmModal.value = true;
    };

    // 处理确认删除
    const handleConfirmDelete = async () => {
      if (!itemToDelete.value) return;

      try {
        if (itemType.value === 'permission') {
          await permissionStore.deletePermission(itemToDelete.value.id);
        } else {
          await permissionStore.deletePermissionGroup(itemToDelete.value.id);
        }
        
        // 重新加载数据
        fetchPermissionGroups();
        // 可以在这里添加成功提示
      } catch (error) {
        console.error(`删除${itemType.value === 'permission' ? '权限' : '权限组'}失败:`, error);
        // 可以在这里添加错误提示
      } finally {
        showConfirmModal.value = false;
        itemToDelete.value = null;
        itemType.value = '';
      }
    };

    // 保存权限
    const handleSavePermission = async (permission) => {
      try {
        if (permission.id) {
          await permissionStore.updatePermission(permission.id, permission);
        } else {
          await permissionStore.createPermission(permission);
        }
        
        // 重新加载数据
        fetchPermissionGroups();
        showAddPermissionModal.value = false;
        showEditPermissionModal.value = false;
        // 可以在这里添加成功提示
      } catch (error) {
        console.error(`${permission.id ? '更新' : '创建'}权限失败:`, error);
        // 可以在这里添加错误提示
      }
    };

    // 保存权限组
    const handleSaveGroup = async (group) => {
      try {
        if (group.id) {
          await permissionStore.updatePermissionGroup(group.id, group);
        } else {
          await permissionStore.createPermissionGroup(group);
        }
        
        // 重新加载数据
        fetchPermissionGroups();
        showAddGroupModal.value = false;
        showEditGroupModal.value = false;
        // 可以在这里添加成功提示
      } catch (error) {
        console.error(`${group.id ? '更新' : '创建'}权限组失败:`, error);
        // 可以在这里添加错误提示
      }
    };

    // 重置筛选条件
    const resetFilters = () => {
      searchQuery.value = '';
      selectedGroupId.value = '';
    };

    // 页面加载时初始化
    onMounted(() => {
      fetchPermissionGroups();
    });

    return {
      permissionGroups,
      loading,
      searchQuery,
      selectedGroupId,
      showAddPermissionModal,
      showEditPermissionModal,
      showAddGroupModal,
      showEditGroupModal,
      showConfirmModal,
      selectedPermission,
      selectedGroup,
      confirmTitle,
      confirmMessage,
      filteredGroups,
      fetchPermissionGroups,
      toggleGroup,
      isGroupOpen,
      loadPermissionsByGroup,
      editPermission,
      editGroup,
      confirmDeletePermission,
      confirmDeleteGroup,
      handleConfirmDelete,
      handleSavePermission,
      handleSaveGroup,
      resetFilters
    };
  }
};
</script>

<style scoped>
.permission-settings-container {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .action-bar .flex {
    flex-direction: column;
    align-items: stretch;
  }
  
  .permission-list {
    font-size: 14px;
  }
  
  .permission-list .px-6 {
    padding-left: 1rem;
    padding-right: 1rem;
  }
  
  .permission-list .pl-16 {
    padding-left: 3rem;
  }
}
</style>
    